<template>
  <div class="roles">
  <!-- 面包屑 -->
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item :to="{ path: '/roles' }">权限管理</el-breadcrumb-item>
        <el-breadcrumb-item>角色列表</el-breadcrumb-item>
      </el-breadcrumb>
    <!-- 添加角色 -->
      <el-button type="primary" plain @click="addDialogFormVisible=true">添加角色</el-button>
    <!-- 表格 -->
      <el-table
      class="mt-15"
      :data="rolesList"
      border
      style="width: 100%">
        <el-table-column type="expand">
          <template slot-scope="scope">
            <!-- 第一层循环 -->
            <el-row v-for="(firstItem,index) in scope.row.children" :key="index">
              <el-col :span="4">
                <el-tag closable @close="handleClose(scope.row,firstItem.id)">{{firstItem.authName}}</el-tag>
              </el-col>
              <el-col :span="20">
                <!-- 第二层循环 -->
                <el-row v-for="(secondItem,index) in firstItem.children" :key="index" style="margin-bottom:10px;border-top:1px solid #ccc">
                  <el-col :span="4">
                    <el-tag type="success" closable @close="handleClose(scope.row,secondItem.id)">{{secondItem.authName}}</el-tag>
                  </el-col>
                  <el-col :span="20">
                    <!-- 第三层循环 -->
                    <el-tag type="warning" closable style="margin:0 5px"  v-for="(thirdItem,index) in secondItem.children" :key="index" @close="handleClose(scope.row,thirdItem.id)">{{thirdItem.authName}}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column
          type="index"
          width="50">
        </el-table-column>
        <el-table-column
          prop="roleName"
          label="角色名称">
        </el-table-column>
        <el-table-column
          prop="roleDesc"
          label="描述">
        </el-table-column>
        <el-table-column
          label="操作">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" plain icon="el-icon-edit" @click="handleEditRoles(scope.row)"></el-button>
            <el-button size="mini" type="danger" plain icon="el-icon-delete" @click="handleDelRoles(scope.row.id)"></el-button>
            <el-button size="mini" type="warning" plain icon="el-icon-check" @click="handleAuthRoles(scope.row)"></el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 添加角色对话框 -->
      <el-dialog title="添加角色" :visible.sync="addDialogFormVisible">
        <el-form :model="addForm" ref="addForm" :rules="rules">
          <el-form-item label="角色名称" :label-width="formLabelWidth" prop="roleName">
            <el-input v-model="addForm.roleName" auto-complete="off"></el-input>
          </el-form-item>
          <el-form-item label="角色描述" :label-width="formLabelWidth" prop="roleDesc">
            <el-input v-model="addForm.roleDesc" auto-complete="off"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="addDialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitAddRoles('addForm')">确 定</el-button>
        </div>
      </el-dialog>
      <!-- 编辑角色对话框 -->
      <el-dialog title="添加角色" :visible.sync="editDialogFormVisible">
        <el-form :model="editForm" ref="editForm" :rules="rules">
          <el-form-item label="角色名称" :label-width="formLabelWidth" prop="roleName">
            <el-input v-model="editForm.roleName" auto-complete="off"></el-input>
          </el-form-item>
          <el-form-item label="角色描述" :label-width="formLabelWidth" prop="roleDesc">
            <el-input v-model="editForm.roleDesc" auto-complete="off"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="editDialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitEditRoles('editForm')">确 定</el-button>
        </div>
      </el-dialog>
      <!-- 角色授权对话框 -->
      <el-dialog title="授权角色" :visible.sync="authDialogFormVisible">
        <el-tree
          ref="tree"
          class="tree-box"
          :data="treeData"
          show-checkbox
          node-key="id"
          :default-checked-keys="checkedList"
          default-expand-all
          :props="defaultProps">
        </el-tree>
        <div slot="footer" class="dialog-footer">
          <el-button @click="authDialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitAuthRoles('authForm')">确 定</el-button>
        </div>
      </el-dialog>
  </div>
</template>

<script>
import { getRolesList, postAddRoles, deleteRoles, putEditRoles, deleteRolesRights, getAllRightsList, postRolesAuthSubmit } from '@/api'
export default {
  data () {
    return {
      rolesList: [],
      addForm: { roleName: '', roleDesc: '' },
      editForm: { roleName: '', roleDesc: '' },
      addDialogFormVisible: false,
      editDialogFormVisible: false,
      authDialogFormVisible: false,
      treeData: [],
      rolesId: '',
      defaultProps: {
        children: 'children',
        label: 'authName'
      },
      checkedList: [], // 一开始被选中的
      formLabelWidth: '100px',
      rules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' }
        ],
        roleDesc: [
          { required: true, message: '请输入角色描述', trigger: 'blur' }
        ]

      }
    }
  },
  created () {
    this.initTable()
  },
  methods: {
    // 表格初始化
    initTable () {
      getRolesList().then(res => {
        // console.log(res)
        this.rolesList = res.data
      })
    },
    // 添加角色
    submitAddRoles (formName) {
      this.$refs[formName].validate(isPass => {
        if (isPass) {
          postAddRoles(this.addForm.roleName, this.addForm.roleDesc).then(res => {
            // console.log(res)
            if (res.meta.status === 201) {
              this.$message.success(res.meta.msg)
              this.initTable()
              this.addDialogFormVisible = false
            }
          })
        }
      })
    },
    // 删除角色
    handleDelRoles (id) {
      deleteRoles(id).then(res => {
        // console.log(res)
        if (res.meta.status === 200) {
          this.$message.success(res.meta.msg)
          this.initTable()
        }
      })
    },
    // 编辑角色
    handleEditRoles (row) {
      // console.log(row)
      this.editDialogFormVisible = true
      this.editForm['roleName'] = row.roleName
      this.editForm['roleDesc'] = row.roleDesc
      this.editForm['id'] = row.id
    },
    // 编辑角色提交
    submitEditRoles (formName) {
      this.$refs[formName].validate(isPass => {
        if (isPass) {
          putEditRoles(this.editForm.id, this.editForm.roleName, this.editForm.roleDesc).then(res => {
            // console.log(res)
            if (res.meta.status === 200) {
              this.$message.success('编辑成功！')
              this.editDialogFormVisible = false
              this.initTable()
            }
          })
        }
      })
    },
    // 删除角色指定权限
    handleClose (row, rightId) {
      deleteRolesRights(row.id, rightId).then(res => {
        // console.log(res)
        if (res.data.meta.status === 200) {
          // 返回的数据包含新的权限列表，直接替换数据，避免重新发请求
          row.children = res.data.data
        }
      })
    },
    // 角色授权
    handleAuthRoles (row) {
      // 保存角色id
      this.rolesId = row.id
      this.checkedList = []
      getAllRightsList('tree').then(res => {
        // console.log(res)
        this.authDialogFormVisible = true
        this.treeData = res.data
        this._getRightsId(row.children, this.checkedList)
      })
    },
    // 获取第三层的权限id
    _getRightsId (data, arr) {
      data.forEach(firstItem => {
        if (firstItem.children) {
          firstItem.children.forEach(secondItem => {
            if (secondItem.children) {
              secondItem.children.forEach(item => {
                arr.push(item.id)
              })
            }
          })
        }
      })
    },
    // 角色授权提交
    submitAuthRoles () {
      let keySon = this.$refs.tree.getCheckedKeys()
      let keyFather = this.$refs.tree.getHalfCheckedKeys()
      // 将两个数组合并
      let dataArr = [...keySon, ...keyFather]
      // 将数组转换成用逗号连接的字符串
      let dataStr = dataArr.join(',')
      // console.log(dataStr)
      postRolesAuthSubmit(this.rolesId, dataStr).then(res => {
        // console.log(res)
        if (res.meta.status === 200) {
          this.$message.success('更新成功！')
          this.authDialogFormVisible = false
          this.initTable()
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.tree-box{
  height: 300px;
  overflow: auto;
}
</style>
